#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <functional>
#include <unordered_map>
#include "Protocol.hpp"
#include "Util.hpp"
namespace Server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };

    using namespace std;

    static const uint16_t gport = 8080;
    static const uint16_t gbacklog = 5;

    using func_t=std::function<void(const HttpRequst&, HttpResponse&)>;

    class HttpServer
    {
    public:
        HttpServer(func_t func,const uint16_t &port = gport)
            : func_(func),listen_sockfd_(-1), port_(port)
        {
        }

        void InitServer()
        {
            // 1.创建socket
            listen_sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
            if (listen_sockfd_ < 0)
            {
                exit(SOCKET_ERR);
            }

            // 2.bind网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(listen_sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                exit(BIND_ERR);
            }


            // 3.设置socket为监听状态
            if (listen(listen_sockfd_, gbacklog) < 0)
            {
                exit(LISTEN_ERR);
            }
        }

        // void registerCb(string servicename,func_t cb)
        // {
        //     funcs.insert(make_pair(servicename,cb));
        // }

        void HandlerHttp(int sock)
        {
            char buffer[4096];
            HttpRequst req;
            HttpResponse resp;
            size_t n=recv(sock,buffer,sizeof(buffer)-1,0);
            if(n>0)
            {
                buffer[n]=0;
                req.inbuffer=buffer;
                req.parse();
                //funcs[req.path](req,resp);
                func_(req,resp);
                send(sock,resp.outbuffer.c_str(),resp.outbuffer.size(),0);
            
            }
        }


        void start()
        {

            for (;;)
            {
                // 4.server获取新链接
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                // sock:和客户端通信的文件描述符
                int sock = accept(listen_sockfd_, (struct sockaddr *)&peer, &len);
                if (sock < 0) // 没有获取新链接成功就执行下一次循环
                {
                    continue;
                }

                pid_t id = fork();
                if (id == 0) // 子进程
                {
                    close(listen_sockfd_);
                    if (fork() > 0)
                    
                    HandlerHttp(sock);
                    
                    close(sock);
                    exit(0);
                }

                close(sock);
                // 父进程
                pid_t ret = waitpid(id, nullptr, 0);
                
            }
        }

        ~HttpServer()
        {
        }

    private:
        int listen_sockfd_; // 不负责通信，只负责监听链接，获取新链接
        uint16_t port_;
        func_t func_;
        // unordered_map<std::string,func_t> funcs;
    };
}